<?php
		
	/* SVN FILE: $Id: fnUploads.php 16 2011-03-14 20:57:11Z michele.andreoletti@gmail.com $ */
	
	/**
	* Project Name : arcadia
	*
	* @author $Author: michele.andreoletti@gmail.com $
	* @version $Revision: 16 $
	* @lastrevision $Date: 2011-03-14 20:57:11 +0000 (Mon, 14 Mar 2011) $
	* @filesource $URL: http://arcadia.googlecode.com/svn/trunk/include/fnUploads.php $
	*/


	/**
	 *
	 * fnUploadsTabContent
	 *
	 */	
	function fnUploadsTabContent ($iView, $sViewItemLink, $iTab) {
		
		global $sAPP;
		
		global $aData; // mi serve array $aData per verificare se la scheda è nel cestino
			
		$html = '';
		
		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $sViewItemLink, $iTab);
		
		$sUploadsMaxFileSize = fnUploadsFileSizeText(fnUploadsMaxFileSize());
		
		if (is_allowed('edit', $iFieldAccessLvl) && empty($aData['iTrash'])) {

			$html .= "
			<div>
				<div class='gray-text small-text'>Dimensione massima di ciascun allegato: $sUploadsMaxFileSize</div>
				<!-- form to be replaced by uploadify -->
				<form id='uploads-uploadify' action='../include/uploads.php' method='post' enctype='multipart/form-data'>
					<p><input type='file' name='Filedata' /></p>
					<p><input type='submit' name='submit' value='Upload' /></p>
					<input type='hidden' name='iView' value='$iView'/>
					<input type='hidden' name='sViewItemLink' value='$sViewItemLink'/>
					<input type='hidden' name='sAPP' value='$sAPP'/>
					<input type='hidden' name='sRedirect' value='true'/>
				</form>
				<span id='uploads-loader' style='display:none;'><img src='../themes/common/images/indicator.gif' alt='Attendere...' /></span>
			</div>
			
			<div id='uploads-queue'></div>";
		}
		
   		$html .= "<div id='uploads-file-list'>";	
		if (is_allowed('view', $iFieldAccessLvl)) {
			$html .= fnUploadsFileList ('sHtml', $iView, $iTab, $sViewItemLink);	
		} else  {
			$html .= "	<ul><li>Autorizzazione insufficiente per visualizzare gli allegati</li></ul>";
		}	
		$html .= "</div>";
		
		return $html;
	}

	
	/**
	 *
	 * fnUploadsFileList
	 *
	 */		
	function fnUploadsFileList ($sWhat='sHtml', $iView, $iTab, $sViewItemLink) {
		
		global $sAPP;
		
		$html = '';

		$iAccessLvl = fnGetAccessLvl();
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $iTab, 'uploads');
		
		global $aVIEW;
	
		global $aData; // utilizzo aData per verificare se la scheda è nel cestino
			
		$sQuery = fnUploadsAttacchedFilesQuery($iView, $aVIEW[$sViewItemLink]['sViewSelectFrom']);
		$rResult = custom_mysql_query($sQuery, 'fnUploadsAttacchedFilesQuery()');
  		$iUploadsNum = mysql_num_rows($rResult);
		
		if ($sWhat=='iUploadsNum') {
			return $iUploadsNum;
		}
		
		else if ($sWhat=='sHtml') {	
			$html = '';			
			
			if ($iUploadsNum > 0) {
				$html .= "<ul>";
				while ($aRow = mysql_fetch_assoc($rResult)) {
					$html .= "<li>";
					$html .= "		<a href='../include/download.php?iUpload=".$aRow['id']."&iView=$iView&sViewItemLink=$sViewItemLink&sAPP=$sAPP'>
										".fnHtmlFileIcon($aRow['sName'])."</a>&nbsp;
									<a href='../include/download.php?iUpload=".$aRow['id']."&iView=$iView&sViewItemLink=$sViewItemLink&sAPP=$sAPP'>
											<div class='edit file-description' id='".$aRow['id']."'>".(empty($aRow['sDescription']) ? $aRow['sName'] : $aRow['sDescription'])."</div>
									</a>&nbsp;";
					if (is_allowed('edit', $iFieldAccessLvl) && empty($aData['iTrash'])) { 
						$html .= "		<img class='edit-trigger' iUpload='".$aRow['id']."' src='../themes/common/images/icn_pencil.gif' />";
						$html .= "		<a href='#' class='edit-cancel'>Annulla</a>";
					}
					$html .= "		<span class='file-size'>".fnTextFileSize($aRow['iSize'])."</span>";
					$html .= "		<span class='file-lastmodify'>".fnHtmlLastModify($aRow['tsLastModify'], true, "creato")."</span>";
					if (is_allowed('delete', $iFieldAccessLvl) && empty($aData['iTrash'])) { 			
						$html .= "	<span class='file-remove' sName='".$aRow['sName']."' iUpload='".$aRow['id']."'><img src='../themes/common/images/icn_trash.gif' /></span>";
					}	
					$html .= "</li>";
				}			
				$html .= "</ul>";
			} else  {
				$html .= "<ul><li>Nessun documento allegato</li></ul>";
			}
			return $html;

		} else {
			return NULL;

		}
	}


	/**
	 * 
	 * fnUploadsAttacchedFilesQuery
	 *
	 */
	 function fnUploadsAttacchedFilesQuery ($iView, $sViewSelectFrom) {
		global $sAPP;
	 	$sQuery = "SELECT * FROM `uploads` WHERE `iView`='$iView' AND `sApp`='$sAPP' AND `sSelectFrom`='$sViewSelectFrom' ORDER BY `tsLastModify` DESC";
		return $sQuery;
	}


	/**
	 * 
	 * fnUploadsMaxAllowedPackedQuery
	 *
	 */
	 function fnUploadsMaxAllowedPackedQuery () {
		$sQuery = "SHOW VARIABLES LIKE 'max_allowed_packet'";
		return $sQuery;
	}


	/**
	 *
	 * fnUploadsMaxFileSize
	 *
	 * $iUploadsMaxFileSize è uguale al 90% della dimensione massima di una query (max_allowed_packet)
	 *
	 */
	function fnUploadsMaxFileSize () {
		$sQuery = fnUploadsMaxAllowedPackedQuery();
		$rResult = custom_mysql_query($sQuery, 'fnUploadsMaxAllowedPackedQuery()');
		$aRow = mysql_fetch_assoc($rResult);
		$iUploadsMaxFileSize = round($aRow['Value'] * .90);
		return $iUploadsMaxFileSize;	
	}

		
	/**
	 *
	 * fnUploadsFileSizeText
	 *
	 */
	function fnUploadsFileSizeText ($iSize) {
		
		if ($iSize >= (pow(10,6)-1))
			return number_format(($iSize/pow(10,6)),1).' MB';	
		else if ($iSize >= (pow(10,3)-1)) 
			return number_format(($iSize/pow(10,3)),1).' KB';		
		else
			return number_format($iSize,1).' Bytes';	
	
	}
	

	/**
	 *
	 * fnJsRemoveFile
	 *
	 */
	 function fnJsRemoveFile ($iView, $sViewItemLink) {
		
		global $sAPP;

		$sScript = 	"
			function fnRemoveFile(iUpload, oParent) {
				$.getJSON('../include/uploads.remove.php', { 	'sAction': 'Remove',
																'iUpload': iUpload,
																'iView': '$iView',
																'sViewItemLink': '$sViewItemLink',
																'sAPP': '$sAPP' },  function (json) {
					if (json[0].sAction=='Remove' && json[0].sError=='') {
						iStringLength = $('#sUploadsNum').text().length;
						iUploadsNum = $('#sUploadsNum').text().slice(1,iStringLength-1) * 1;
						if (iUploadsNum > 1) {
							oParent.remove();
							addClassOdd();
							$('#sUploadsNum').text('('+(iUploadsNum-1)+')');
						} else {
							oParent.text('Nessun documento allegato');
							$('#sUploadsNum').text('');
						}
					}
				});
			};		";
		return $sScript;	
	}


	/**
	 *
	 * fnJsFileRemoveDialog
	 *
	 */
	function fnJsFileRemoveDialog () {
		$sScript = 	"
			$('#uploads-file-remove-dialog').dialog({
				autoOpen: false,
			  	resizable: false,
				modal: true,
				buttons: {
					'Rimuovi': function() {
						fnRemoveFile(oClicked.attr('iUpload'), oClicked.parents('li'));
						$(this).dialog('close');
					},
					Annulla: function() {
						$(this).dialog('close');
					}
				}
			}); ";
		return $sScript;
	}


	/**
	 *
	 * fnJsFileRemoveClick
	 *
	 */
	function fnJsFileRemoveClick () {
		$sScript = 	"
			$('.file-remove').click(function() {
		  		oClicked = $(this);
		  		$('#uploads-file-remove-dialog-text').text($(this).parent().parent().children('li').children('a').children('div:first').text());
		  		$('#uploads-file-remove-dialog').dialog('open');
				return false;
			});	";
		return $sScript;
	}


	/**
	 *
	 * fnJsFileEditTrigger
	 *
	 */
	 function fnJsFileEditTrigger () {
		$sScript = 	"
			$('.edit-trigger').bind('click', function() {
				$(this).prev('a').contents().unwrap(); // rimuovo <a href=' ...
	  			$('.edit-trigger').hide(); // nascondo <img class='Rename'...
	  			$(this).next('.edit-cancel').show(); // visualizzo link Annulla
				$('#' + $(this).attr('iUpload')).trigger('edit');
		    	return false;
			});	";
		return $sScript;
	}


	/**
	 *
	 * fnJsFileEditCancel
	 *
	 */
	function fnJsFileEditCancel () {
		$sScript = 	"
			$('.edit-cancel').bind('click', function() {
				return false;
			});	";
		return $sScript;
	}	


	/**
	 *
	 * fnJsFileJeditable
	 *
	 */
	 function fnJsFileJeditable () {
		
		global $sAPP;
		
		$sScript = 	"
			$('.edit').editable('../include/uploads.rename.php', {
				placeholder : '&nbsp;',
	        	id : 'iUpload',
        		name : 'sDescription',
        		submitdata : {sAPP: '$sAPP'},
        		event : 'edit',
				height : '22px',
				width : '250px',
				style : 'inherit',
				callback : function(value, settings) {
	        		sLink = $(this).prev().attr('href');
	        		$(this).wrap(\"<a href='\" + sLink + \"'>\"); // aggiungo <a href='..
					$('.edit-trigger').show(); // visualizzo <img class='edit-trigger'...
					$('.edit-cancel').hide(); // nascondo link Annulla
					return false;
    			},
    			onreset : function() {
    				sLink = $(this).parents('div:first').prev().attr('href');
    				// $(this).parents('div').wrap(\"<a href='\" + sLink + \"' />\"); // aggiungo <a href='..
					$('.edit-trigger').show(); // visualizzo <img class='edit-trigger'...
					$('.edit-cancel').hide(); // nascondo link Annulla
  				}		 
			});	";
		return $sScript;
	}
	
	
	/**
	 *
	 * fnHtmlFileIcon
	 *
	 */
	function fnHtmlFileIcon ($sFilename='') {
		$sExt = strtolower(substr($sFilename, strrpos($sFilename, ".")+1));
		$sPath = "../themes/common/images/icons/";
		$sFileIcon = (file_exists($sPath . "$sExt.gif") ? $sPath . "$sExt.gif" : $sPath . "unknown.gif");
		return '<img src="' . $sFileIcon .'" border="0" />';
	}
	
	
	/**
	 *
	 * fnTextFileSize
	 *
	 */
	function fnTextFileSize ($iSize) {
		if ($iSize >= (pow(10,6)-1))
			return number_format(($iSize/pow(10,6)),1).' MB';	
		else if ($iSize >= (pow(10,3)-1)) 
			return number_format(($iSize/pow(10,3)),1).' KB';		
		else
			return number_format($iSize,1).' Bytes';	
	}

	
	/**
	 *
	 * fnUploadsNum
	 * Funzione utilizzata in view.php
	 *
	 */
	function fnUploadsNum ($iView, $sViewSelectFrom, $iTabUploads) {
	
		global $sAPP;
		global $iAccessLvl;
		
		$iUploadsNum = 0;
		$sUploadsNum = '';
		
		$iFieldAccessLvl = fnFieldAccessLvl($iAccessLvl, $iTabUploads);
		
		if (is_allowed('view', $iFieldAccessLvl)) {

			$sQuery = fnUploadsAttacchedFilesQuery($iView, $sViewSelectFrom, $sAPP);
			$rResult = custom_mysql_query($sQuery, 'fnUploadsAttacchedFilesQuery()');
	  		$iUploadsNum = mysql_num_rows($rResult);

		}

		if (!empty($iUploadsNum)) {
			$sUploadsNum = '('.$iUploadsNum.')';
		}
		
		return $sUploadsNum;
	}

?>